/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import com.google.code.morphia.dao.BasicDAO;
import com.google.code.morphia.query.Query;
import entity.News;
import java.util.List;
import org.bson.types.ObjectId;

/**
 *
 * @author xuanhung2401
 */
public class NewsModel extends BasicDAO<News, ObjectId> {

    public NewsModel() {
        super(DBConnection.getMongo(), DBConnection.getMorphia(), DBConnection.getDatabase());
    }

    public List<News> all() {
    	Query<News> q = ds.createQuery(News.class);
        q.field("complete").equals(true); 
        q.field("status").equal(1);
        return q.order("-dog").limit(10).asList();
    }

    public News findById(ObjectId id) {
        return ds.find(News.class, "id", id).get();
    }

    public List<News> findByCategory(String alias){
        Query<News> q = ds.createQuery(News.class);
        q.field("complete").equals(true); 
        q.field("category").equal(alias); 
        return q.asList();
    }
    
    public List<News> findBySubCategory(String alias, int limit){
        Query<News> q = ds.createQuery(News.class);
        q.field("complete").equals(true); 
        q.field("subCategory").equal(alias); 
        return q.order("-dog").limit(limit).asList();  
    }
    
    public News findLatest() {
        return ds.find(entityClazz, "complete", true).order("-dog").limit(1).get();
    }

    public News findRelatedLink(String url) {
        Query<News> q = ds.createQuery(News.class);
        q.field("complete").equals(true); 
        q.field("url").equal(url); 
        return (News) q.get();
    }

    public News findByAlias(String alias) {
        return ds.find(News.class, "alias", alias).get();
    }

    public News findByUrl(String url) {
        return ds.find(News.class, "url", url).get();
    }

    public boolean isExits(String url) {
        return ds.find(News.class, "url", url).get() == null ? false : true;
    }

    public News getFalseComplete() {
    	Query<News> q = ds.createQuery(News.class);
        q.field("complete").equals(false); 
        q.field("status").equal(0);
        News result = (News) q.get();
        if(result!=null){
        	result.setStatus(2);
            save(result);        	
        }        
        return result;
        
    }
}
